package com.lingshi.shopping_manager_api.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.common.entity.Admin;
import com.lingshi.common.result.BaseResult;
import com.lingshi.common.service.AdminService;
import com.lingshi.shopping_manager_api.service.ILoginService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
public class AdminController {
    @DubboReference
    private AdminService adminService;

    @Autowired
    private ILoginService loginService;

//    新增管理员
    @PostMapping("/add")
    public BaseResult add(@RequestBody Admin admin){
        admin.setPassword(SaSecureUtil.md5(admin.getPassword()));
        adminService.add(admin);
        return BaseResult.success();
    }


//    修改管理员
    @PutMapping("/update")
    public BaseResult update(@RequestBody Admin admin){
        admin.setPassword(SaSecureUtil.md5(admin.getPassword()));
        adminService.update(admin);
        return BaseResult.success();
    }

//    删除管理员
    @DeleteMapping("/delete")
    public BaseResult delete(Long aid){
        adminService.delete(aid);
        return BaseResult.success();
    }

//    根据id查询管理员
    @GetMapping("/findById")
    public BaseResult findById(Long aid){
        Admin admin = adminService.findById(aid);
        return BaseResult.success(admin);
    }

//    分页查询管理员
    @GetMapping("/search")
    @SaCheckPermission("/admin/search")//访问此方法时，必须拥有此权限。
    public BaseResult search(@RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer size){
        Page<Admin> search = adminService.search(page, size);
        return BaseResult.success(search);
    }

    @PutMapping("/updateRoleToAdmin")
    public BaseResult updateRoleToAdmin(Long aid, Long[] rids) {
        adminService.updateRoleToAdmin(aid,rids);
        return BaseResult.success();
    }

    @PostMapping("/login")
    public BaseResult login(String username,String password){
        return loginService.login(username, password);
    }

    @PostMapping("/logout")
    public BaseResult logout(){
        //退出登录
        StpUtil.logout();
        return BaseResult.success();
    }

}
